<template>
    <div style="height: 32px;margin-left: 9px;">
        <Button
            type="primary"
            ghost
            icon="ios-add"
            style="margin-bottom: 0;"
            v-if="!hideButton"
            @click="showRelevanceModal">关联{{ typeName }}
        </Button>
        <Modal
            v-model="relevanceModal.show"
            @on-visible-change="changeVisible"
            :title="`关联${typeName}`">
            <Form
                ref="relevanceFormInline"
                :label-width="110"
                :model="relevanceFormInline"
                :rules="relevanceRuleInline">
                <FormItem prop="ids" :label="`可选${typeName}`" class="my-form-item">
                    <Select filterable transfer filterable clearable v-model="relevanceFormInline.ids" placeholder=""
                        multiple :not-found-text="relevanceModal.loadingData ? '获取中' : '无匹配数据'">
                        <Option v-for="item in optionList" :value="item.id" :key="item.id">{{ item.name }}({{ item.version }})</Option>
                    </Select>
                    <Checkbox v-model="single"
                        @on-change="(val) => relevanceFormInline.ids = val ? optionList.map(item => item.id) : []"
                        style="margin-left: 10px;"
                        :disabled="optionList.length === 0">全选</Checkbox>
                </FormItem>
            </Form>
            <div slot="footer" class="footer">
                <Button @click="relevanceModal.show = false">取消</Button>
                <Button @click="addPartToProductBatch" :loading="relevanceModal.loading"  type="primary">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import {
    queryProductPartList,
    addPartToProductBatch
} from '../../asset/api/productPart'
import {
    addModuleToPartBatch,queryProductComponentList
} from '../../asset/api/productComponent'
import {
    addRelativeProduct,queryProductPublicPart
} from '@/view/testPlatform/asset/api/assetCommonComponent'
export default {
    name: 'RelevancePartModule',
    props: {
        type: { // 0：部件  1：组件
            type: Number,
            default: 0
        },
        productId: {
            type: String,
            default: ''
        },
        hideButton: {
            type: Boolean,
            default: false
        },
        partId: {
            type: String,
            default: ''
        },
        isPublic: {
            type: Boolean, // 是否公共部件或组件
            default: false
        }
    },
    watch: {
        'relevanceFormInline.ids': function(list) {
            this.single = list.length === this.optionList.length
        }
    },
    computed: {
        typeName() {
            return this.type === 0 ? `${this.isPublic ? '公共' : ''}部件` : `${this.isPublic ? '公共' : ''}组件`
        }
    },
    data() {
        return {
            single: false,
            relevanceModal: {
                show: false,
                loading: false,
                loadingData: false
            },
            optionList: [],
            relevanceFormInline: {
                ids: [],
            },
            relevanceRuleInline: {
                ids: [
                    { required: true, type:'array', message: '请选择要关联的数据', trigger: 'blur,change' }
                ]
            },
        }
    },
    methods: {
        // 隐藏模态框时，重置表单数据
        changeVisible(type) {
            if (!type) {
                this.$refs.relevanceFormInline.resetFields()
                this.single = false
                this.relevanceModal.loading = false
                this.relevanceModal.loadingData = false
            }
        },
        // 打开关联部件的模态框，初始化数据
        showRelevanceModal() {
            this.relevanceModal.show = true
            this.relevanceModal.loadingData = true
            this.optionList = []
            let selfApiName = this.type === 0 ? queryProductPartList : queryProductComponentList
            let targetApiName = this.type === 0 
                ? queryProductPartList 
                : queryProductComponentList
            Promise.all([selfApiName({
                pageIndex: 1,
                pageSize: 2147483646,
                productId: this.productId,
                partId: this.type === 1 ? this.partId : undefined
            }), targetApiName({
                pageIndex: 1,
                pageSize: 2147483646,
                isPublic: this.isPublic ? 'Y': 'N'
            })]).then(res => {
                let selfIds = [], allOptionList = [], companyId = ''
                res.forEach((item, index) => {
                    let { code, data } = item
                    if (index === 0) { // 本资产已有的部件
                        if (code === 1) {
                          let list = data.items || []
                            selfIds = list.map(item => item.id)
                            companyId = list.length ? list[0].companyId : ''
                        }
                    } else { // 其他部件
                        if (code === 1) {
                          allOptionList = data.items || []
                        }
                    }
                })
                this.optionList = allOptionList.filter(item => !selfIds.includes(item.id) && (!companyId || companyId === item.companyId))
                this.relevanceModal.loadingData = false
            })
        },
        // 将部件关联至资产、组件关联至部件
        addPartToProductBatch() {
            this.$refs.relevanceFormInline.validate(valid => {
                if (valid) {
                    this.relevanceModal.loading = true
                    let myPromise = this.type === 0 
                        ? addPartToProductBatch(this.productId, this.relevanceFormInline.ids, this.type) 
                        : addModuleToPartBatch(this.partId, this.relevanceFormInline.ids)
                    myPromise.then(({ code, message }) => {
                        if (code !== 1) {
                            this.$Message.warning(message)
                            return
                        }
                        this.$Message.success(`关联${this.typeName}成功`)
                        this.$emit('relevance-success')
                        this.relevanceModal.show = false
                    }).catch(() => {
                        this.$Message.error(`关联${this.typeName}异常`)
                    }).finally(() => {
                        this.relevanceModal.loading = false
                    })
                }
            })
        },
    }
}
</script>

<style scoped>
.my-form-item {
    position: relative;
}
.my-form-item /deep/ .ivu-form-item-content {
    display: flex;
}
.my-form-item /deep/ .ivu-select {
    width: calc(100% - 66px);
}
.my-form-item /deep/ .ivu-form-item-content .ivu-checkbox-wrapper {
    margin-left: 10px;
    width: 66px;
}
</style>
